import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/mysql';
import { verifyToken } from '@/lib/auth';
import { QUESTION_BANK } from '@questions';

// 导出问题题目报告
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    const token = request.cookies.get('token')?.value;
    if (!token) {
      return NextResponse.json({ error: '未登录' }, { status: 401 });
    }

    const payload = verifyToken(token);
    if (!payload || payload.role !== 'admin') {
      return NextResponse.json({ error: '无权限' }, { status: 403 });
    }

    const userId = payload.userId;

    // 获取所有问题题目
    const [problems] = await db.query(
      `SELECT question_id, topic_id, topic_name, question_index, status, issue_type, notes, reviewed_at
       FROM question_reviews
       WHERE reviewed_by = ? AND status IN ('incorrect', 'marked')
       ORDER BY topic_id, question_index`,
      [userId]
    ) as any;

    // 构建Markdown报告
    let markdown = '# 题库质量检测报告\n\n';
    markdown += `**生成时间**: ${new Date().toLocaleString('zh-CN')}\n\n`;
    markdown += `**检测人**: Admin\n\n`;
    markdown += `**问题题目总数**: ${problems.length}\n\n`;
    markdown += '---\n\n';

    // 按知识点分组
    const problemsByTopic: any = {};
    for (const p of problems) {
      if (!problemsByTopic[p.topic_id]) {
        problemsByTopic[p.topic_id] = {
          topicName: p.topic_name,
          problems: []
        };
      }
      problemsByTopic[p.topic_id].problems.push(p);
    }

    // 生成报告内容
    for (const [topicId, data] of Object.entries(problemsByTopic)) {
      const topicData = data as any;
      markdown += `## ${topicData.topicName} (${topicId})\n\n`;
      markdown += `问题题目数: ${topicData.problems.length}\n\n`;

      for (const p of topicData.problems) {
        markdown += `### 题目 #${p.question_index + 1}\n\n`;
        
        // 获取题目详情
        const questions = QUESTION_BANK[p.topic_id];
        if (questions && questions[p.question_index]) {
          const q = questions[p.question_index];
          markdown += `**题目**: ${q.stem}\n\n`;
          markdown += `**答案**: ${q.answer}\n\n`;
          if (q.solution) {
            markdown += `**解析**: ${q.solution}\n\n`;
          }
        }

        markdown += `**问题类型**: ${getIssueTypeText(p.issue_type)}\n\n`;
        markdown += `**状态**: ${getStatusText(p.status)}\n\n`;
        if (p.notes) {
          markdown += `**备注**: ${p.notes}\n\n`;
        }
        markdown += `**检测时间**: ${new Date(p.reviewed_at).toLocaleString('zh-CN')}\n\n`;
        markdown += '---\n\n';
      }
    }

    // 返回Markdown文本
    return new NextResponse(markdown, {
      headers: {
        'Content-Type': 'text/markdown; charset=utf-8',
        'Content-Disposition': `attachment; filename="question-review-report-${Date.now()}.md"`
      }
    });

  } catch (error: any) {
    console.error('导出报告失败:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

function getIssueTypeText(type: string): string {
  const types: any = {
    'answer_wrong': '答案错误',
    'solution_unclear': '解析不清',
    'question_wrong': '题目错误',
    'other': '其他问题'
  };
  return types[type] || '未知';
}

function getStatusText(status: string): string {
  const statuses: any = {
    'incorrect': '答错',
    'marked': '已标记'
  };
  return statuses[status] || status;
}

